/**
 * 获取同色系不同亮度颜色
 * @param {string} color 原色
 * @param {'dark' | 'light' | 'default'} style 亮度：dark/light
 * @param {number} [alpha]
 */

function colorTransform(color, style, alpha) {
  const reg = /rgba?\((\d+),(\d+),(\d+),?(\d+)?\)/;
  const rgb = reg.exec(color);
  const R = +rgb[1] / 255;
  const G = +rgb[2] / 255;
  const B = +rgb[3] / 255;
  const Cmax = Math.max(R, G, B);
  const Cmin = Math.min(R, G, B);
  const V = Cmax - Cmin;

  let H = 0;
  if (V === 0) {
    H = 0;
  } else if (Cmax === R) {
    H = 60 * (((G - B) / V) % 6);
  } else if (Cmax === G) {
    H = 60 * ((B - R) / V + 2);
  } else if (Cmax === B) {
    H = 60 * ((R - G) / V + 4);
  }

  H = Math.floor(backCycle(H, 360));
  let L = numberFixed((Cmax + Cmin) / 2);
  let S = V === 0 ? 0 : numberFixed(V / (1 - Math.abs(2 * L - 1)));

  if (style === 'deep') {
    L = L - 0.15;
    S = S - 0.15;
  } else if (style === 'light') {
    L = L + 0.15;
  }

  let A = 1;
  if (rgb[4] !== undefined) {
    A = rgb[4];
  }
  if (alpha) {
    A = alpha;
  }
  return `hsla(${H},${numberFixed(100 * S)}%,${numberFixed(100 * L)}%,${A})`;
}

function backCycle(num, cycle) {
  let index = num % cycle;
  if (index < 0) {
    index += cycle;
  }
  return index;
}

function numberFixed(num = 0, count = 3) {
  const power = Math.pow(10, count);
  return Math.floor(num * power) / power;
}

export default colorTransform;
